import wsh from './WebSocketHelper.js';
import msg from './Message.js';
import helper from './helper.js'


var WSHelper = null;

/** vue 对象 */
function AppChatInit(v) {
	v.messages = helper.GetSesstion();
	uni.getSystemInfo({
		success: function(res) {

			var clientInfo = plus.push.getClientInfo();
			if (!clientInfo.clientid) {
				setTimeout(function(){
					AppChatInit(v);
				},500);
				return ;
			}
			
			v.clientid = clientInfo.clientid;

			WSHelper = new wsh.WebSocketHelper({
				uuid: clientInfo.clientid,
				projectToken: "6D7-BB91-13901823A235",
				parameter: JSON.stringify({
					headImg: "http://ww2.sinaimg.cn/large/c0b9b2c8jw1epxob2qiwfj20g90g63z2.jpg", // 对方会话列表显示头像
					userName: "健健", // 对方会话列表显示名称
					age: 25,
					client: res.platform
				}),
				url: ''
			}, {
				connect: uni.connectSocket,
				onopen: uni.onSocketOpen,
				onmessage: uni.onSocketMessage,
				onclose: uni.onSocketClose,
				send: uni.sendSocketMessage
			},v);

			WSHelper.onopen(() => {
				console.log("onopen")
			});

			WSHelper.onnetwork((e) => {
				console.log('onnetwork:' + e)
			});

			WSHelper.onclose(() => {
				console.log("onclose")
			});

			WSHelper.onmessage((e) => {

				var result = JSON.parse(e.data);

				switch (result.type) {

					case 'length':
						msg.Task(v, result.type, result.length);
						break;

					case 'offline':
					case 'userlogin':
						msg.Task(v, result.type, result.date);
						break;

					case 'current':
						msg.Task(v, result.type, result);
						break;

					case 'clients':
						for (var i = 0; i < result.date.length; i++) {

							var item = result.date[i];

							if (item.Value.User.Parameter) {

								var reg = new RegExp("'", "g")
								var parameter = JSON.parse(item.Value.User.Parameter.replace(reg, '"'));

								if (parameter && parameter.client == res.platform) {
									WSHelper.OutLogin(item.Value['ServiceToken']);
								}
							}
						}
						break;

					default:
						msg.Task(v, result.type, result);
						break;

				}

			});

		}
	});
}

export default {
	Init: AppChatInit,
	Task: function(v, temp) {

		WSHelper.send({
			Content: temp.msg.content.text,
			MessageKey: v.sesstion,
			MessageType: 0,
			Parameter: JSON.stringify({
				type: temp.msg.type,
				length: temp.msg.content.length
			})
		}, function() {
			console.log('发送成功')
		}, function() {
			console.log('发送失败')

		});

		msg.Send(v, temp);
	},
	
	Reload:function(){
		if(WSHelper) WSHelper.showReload();
	}
}
